<?php

namespace App\Model\Setting;

use App\Model\PayOrder;
use App\Model\Service\CacheService;
use App\Model\UserProfile;
use Hyperf\DbConnection\Model\Model;

/**
 *  礼物分配模型类
 */
class SettingAllocate extends Model
{
    protected $table = 'setting_allocate';

    //男用户分类
    const MALE_CATE_PAY = 1;
    const MALE_CATE_UNPAY = 2;
    const MALE_CATE = [
        self::MALE_CATE_PAY => '已经充值过的',
        self::MALE_CATE_UNPAY => '还未充值过的',
    ];

    //主播分类
    const HOST_CATE = [
        UserProfile::HOST_CATE_A => 'A类主播',
        UserProfile::HOST_CATE_B => 'B类主播',
        UserProfile::HOST_CATE_C => 'C类主播',
    ];

    /**
     * 获取所有对应配置
     */
    static function getAllSetting()
    {
        return self::where(['flag' => 1])->orderBy('priority', 'desc')->get()->toArray();
    }

    /**
     * 根据分类筛选出男用户ID分配的主播群
     */
    static function getHostGroupByUser($userId = 0): array
    {
        //充值数量
        $checkPay = PayOrder::checkSuccessCount($userId);
        $allocateGroup = [];
        $settings = self::getAllSetting();
        foreach ($settings as $setting) {
            $item = [
                'host_cate' => $setting['host_cate'],
                'gift_id' => $setting['gift_id'],
                'gift_num' => $setting['gift_num'],
                'single_gift_num' => $setting['single_gift_num'],
                'gift_expire_time' => $setting['gift_expire_time'],
            ];
            switch ($setting['male_cate']) {
                case self::MALE_CATE_PAY:
                    $checkPay && $allocateGroup[] = $item;
                    break;
                case self::MALE_CATE_UNPAY:
                    !$checkPay && $allocateGroup[] = $item;
                    break;
            }
        }
        return $allocateGroup;
    }

    /**
     * 获取有效分类主播
     */
    static function getAllocateHosts($cate = UserProfile::HOST_CATE_A): array
    {
        $hostIds = CacheService::getHostsByCate($cate);
        $onlineHostIds = UserProfile::getOnlineUsers(UserProfile::ROLE_HOST, 200);
        $onlineIds = array_intersect($hostIds, $onlineHostIds);
        $notOnlineIds = array_diff($hostIds, $onlineHostIds);
        shuffle($onlineIds);
        shuffle($notOnlineIds);
        $hostIds = array_merge($onlineIds, $notOnlineIds);
        return $hostIds;
    }

    static function getGiftIds()
    {
        return self::where(['flag' => 1])->pluck('gift_id')->toArray();
    }
}
